package com.qinghe.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegHtml {

	/**
	 * 取得字符串里面的链接文件名称
	 * 
	 * @param html
	 */
	public static List<String> getUrl(String html) {
		String regex;
		List<String> list = new ArrayList<String>();
		regex = "src=\"(.*?)\"|href=\"(.*?)\"";
		Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
		Matcher matcher = pattern.matcher(html);
		while (matcher.find()) {
			//int begin = matcher.group().indexOf("\"") + 1;
			int begin = matcher.group().lastIndexOf("/") + 1;
			int end = matcher.group().lastIndexOf("\"");
			list.add(matcher.group().substring(begin, end));
		}
		return list;
	}

	/**
	 * 取得字符串里面的图片链接
	 * 
	 * @param html
	 */
	public static List<String> getImgUrl(String html) {
		String regex;
		List<String> list = new ArrayList<String>();
		regex = "img.*?src=\"(.*?)\"";
		Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
		Matcher matcher = pattern.matcher(html);
		while (matcher.find()) {
			list.add(matcher.group(1));
		}
		return list;
	}

	/**
	 * 去除内容中的html代码
	 * 
	 * @param html
	 * @param length
	 */
	public static String splitAndFilterString(String html, int length) {
		if (html == null || html.trim().equals("")) {
			return "";
		}
		// 去掉所有html元素
		String str = html.replaceAll("//&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		int len = str.length();
		if (len <= length) {
			return str;
		} else {
			str = str.substring(0, length);
			str += "......";
		}
		return str;
	}

	public static void main(String args[]) {
		String str = "testafd<a href=\"/feing/attachment/xheditor/link/20140322/201403221509240225.txt\">点击打开链接</a>fdsaf"
				+ "我啊<img alt=\"\" src=\"/feing/attachment/xheditor/img/20140322/201403221509370284.jpg\" />df"
				+ "<img src=\"/feing/attachment/xheditor/img/20140322/201403221514040986.gif\" alt=\"\" />123"
				+ "<embed type=\"application/x-shockwave-flash\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000\" src=\"/feing/attachment/xheditor/flash/20140322/201403221523480815.swf\" wmode=\"opaque\" quality=\"high\" menu=\"false\" play=\"true\" loop=\"true\" allowfullscreen=\"true\" />"
				+ "<embed type=\"application/x-mplayer2\" classid=\"clsid:6bf52a52-394a-11d3-b153-00c04f79faa6\" src=\"/feing/attachment/xheditor/b6767ced70ae4dbbb51952e4525a8db9/media201403221602390604.mp4\" enablecontextmenu=\"false\" autostart=\"false\"/>";
		List<String> list = getImgUrl(str);
		for (String s : list) {
			System.out.println(s);
		}
		
		System.out.println(splitAndFilterString(str, 20));
	}

}
